package com.u.social.article.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.util.ObjectBuilder;
import com.u.social.article.repository.ArticleIndexRepository;
import com.u.social.article.entity.ArticleIndex;
import com.u.social.article.service.IArticleIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: u-social
 * @description: 帖子索引实现类
 * @author: Alex Wu
 * @createDate: 2025-03-03 17:44
 **/

@Service
public class ArticleIndexServiceImpl implements IArticleIndexService {

    @Autowired
    private ArticleIndexRepository articleIndexRepository;


    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Override
    public ArticleIndex save(ArticleIndex articleIndex) {
        ArticleIndex index = articleIndexRepository.save(articleIndex);
        return index;
    }

    @Override
    public List<String> findRecommendEntryByKeyword(String keyword) {
        try{
        // 构建查询请求，根据关键字查询匹配的词条（假设词条在索引中存储）
        SearchRequest searchRequest = new SearchRequest.Builder()
                .query(q -> q.match(m -> m.field("title").query(keyword)))  // 通过标题进行匹配
                .size(10)  // 只返回前 10 个匹配的词条
                .build();

        // 执行查询
        SearchResponse<ArticleIndex> searchResponse = elasticsearchClient.search(searchRequest, ArticleIndex.class);
            // 处理查询结果
            return searchResponse.hits().hits().stream()
                    .map(hit -> hit.source().getTitle())  // 假设我们只需要返回标题作为推荐词条
                    .collect(Collectors.toList());

        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }


        /**
         * 根据关键字查询推荐文章, 基础功能，实际上需要结合语义搜索来完成
         * @param keyword
         * @return
         * @throws IOException
         */
    @Override
    public List<ArticleIndex> findRecommendArticleByKeyword(String keyword) throws IOException {
        try {
            BoolQuery.Builder boolQueryBuilder = QueryBuilders.bool()
                    .should(q -> q.match(m -> m.field("title").query(keyword).boost((float) 2L)))
                    .should(q -> q.match(m -> m.field("content").query(keyword).boost((float) 1L)))
                    .minimumShouldMatch(String.valueOf(1)); // 至少匹配一个条件

            // 构建查询请求
            SearchRequest searchRequest = new SearchRequest.Builder()
                    .query((Function<Query.Builder, ObjectBuilder<Query>>) boolQueryBuilder.build()) // 使用构建的 BoolQuery
                    .sort(s -> s.field(f -> f.field("likeCount").order(SortOrder.Desc)))  // 按 likeCount 排序
                    .sort(s -> s.field(f -> f.field("createTime").order(SortOrder.Desc))) // 按创建时间排序
                    .size(10)  // 只取前 10 条
                    .build();

            // 执行查询
            SearchResponse<ArticleIndex> searchResponse = elasticsearchClient.search(searchRequest, ArticleIndex.class);

            // 处理查询结果
            return searchResponse.hits().hits().stream()
                    .map(hit -> hit.source())
                    .collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
